const _menus = require('./data/menus')
const _products = require('./data/products')
let uid = _products.length + 1

module.exports = function (app) {
  // 获取一件商品
  app.get('/product', (req, res) => {
    let { id } = req.query
    id = parseInt(id)
    const product = _products.find(p => p.id === id)
    if (product) {
      res.status(200).json(product)
    } else {
      res.status(200).json({ code: 404, msg: 'not found' })
    }
  })

  // 分页查询商品列表 (按关键字筛选)
  app.get('/products', (req, res) => {
    let { page = 1, pageSize = 3, search = '' } = req.query
    search = search.toLowerCase()
    const products = _products.filter(
      prod => prod.title.toLowerCase().indexOf(search) > -1
    )
    res.status(200).json({
      products: products.slice(
        (page-1) * pageSize, page * pageSize
      ),
      total: products.length
    })
  })

  // 删除指定商品
  app.delete('/products', (req, res) => {
    let { id } = req.body
    id = parseInt(id)
    const index = _products.findIndex(p => p.id == id)
    if (index > -1) {
      _products.splice(index, 1)
      res.status(200).json({ code: 200, msg: 'ok' })
    } else {
      res.status(200).json({ code: 404, msg: 'not found' })
    }
  })
  
  // 上传图片
  app.post('/products/upload', (req, res) => {
    if (!req.files)
      return res.status(400).json({ code: 404, msg: 'no file uploaded' })

    const { file } = req.files
    file.mv('./img/' + file.name)
    res.status(200).json({
      code: 200,
      msg: 'ok',
      path: '/img/' + file.name
      /*
      data: {
        name: file.name,
        mimetype: file.mimetype,
        size: file.size
      }
      */
    })
  })

  // 添加商品
  app.post('/products', (req, res) => {
    const { title, price, pic, detail } = req.body
    _products.unshift({
      id: uid++,
      title, price, pic, detail
    })
    res.status(200).json({ code: 200, msg: 'ok' })
  })

  // 编辑商品
  app.put('/products', (req, res) => {
    const { id, title, price, pic, detail } = req.body
    const product = _products.find(p => p.id === id)
    if (product) {
      if (title) product.title = title
      if (price !== undefined) product.price = price
      if (pic) product.pic = pic
      if (detail) product.detail = detail
      res.status(200).json({ code: 200, msg: 'ok' })
    } else {
      res.status(200).json({ code: 404, msg: 'not found' })
    }
  })

  // 获取菜单列表
  app.get('/menus', (req, res) => {
    res.status(200).json(_menus)
  })
}
